<template>
  <div class="detail email-detail" v-show="isEndAll" :style="{height:$height-131+'px'}">
    <div class="detail-left" >
      <h1 class="title">
        <i @click="back" title="返回上一页" class="iconfont icon-fanhui"></i>
        <!--按钮组-->
        <el-button size="mini" type="primary" @click="rollBack"
                   v-if="content.emailType==1">回复
        </el-button>
        <el-button size="mini" type="primary" @click="toEdit"
                   v-if="content.boxId==3||content.emailType==0">再次编辑
        </el-button>
        <el-button size="mini" type="primary" title="进入邮件详情回复" @click="toBack(0)"
                   v-if="content.emailType==1||content.emailType==0">回复全部
        </el-button>
        <el-button type="default" size="mini" @click="translate"
                   v-if="content.boxId==0||(content.boxId==7&&content.emailType==1)">分 发
        </el-button>
        <el-select class="next-deal" v-model="targetTime" @change="toNextDeal" size="mini" style="width: 100px"
                   v-if="content.boxId!=4&&content.boxId!=5"
                   placeholder="稍后处理">
          <el-option value="" label="稍后处理" hidden></el-option>
          <el-option value="1">今天 &nbsp;&nbsp;<span>{{todayTime}}</span></el-option>
          <el-option value="2">明天 &nbsp;&nbsp;<span>08:00</span></el-option>
          <el-option value="3">后天 &nbsp;&nbsp;<span>08:00</span></el-option>
          <el-option value="4">下周{{nextWeek}} &nbsp;&nbsp;<span>08:00</span></el-option>
          <el-option value="稍后处理" class="spec" style="cursor: pointer">
            自定义时间 &nbsp;&nbsp;<i class="el-icon-arrow-right"></i>
          </el-option>
        </el-select>
        <el-select v-model="targetLabel" @change="toLabel" size="mini" placeholder="标记为" style="width: 85px;"
                   v-if="content.boxId!=4&&content.boxId!=5">
          <el-option value="" label="标记为" hidden></el-option>
          <el-option :value="item.id" v-for="item in common.labelList" :key="item.id">
            <b :style="{display:'inline-block',
              width: '10px',height: '10px',borderRadius: '2px',backgroundColor: item.labelColor,marginRight: '2px'}"></b>{{item.labelName}}
          </el-option>
          <el-option value="add" style="color: #2A97F9">+新建标签并标记</el-option>
        </el-select>
        <el-select v-model="targetRemove" @change="toRemove" size="mini" placeholder="移动到" style="width: 85px;"
                   v-if="content.boxId==7">
          <el-option value="" label="移动到" hidden></el-option>
          <el-option label="已删除" value="4" v-show="content.boxId!=4"></el-option>
          <el-option label="垃圾邮件" value="5" v-show="content.boxId!=5"></el-option>
          <el-option label="归档文件" value="7" v-show="content.boxId!=7"></el-option>
        </el-select>
        <el-button @click="elseEmail()" size="mini" style="width: 107px;"
                   v-show="content.boxId==7&&content.emailType==1" :loading="isComplete">{{isComplete?'附件生成中':'作为附件转发'}}</el-button>
        <el-button @click="emptyEmail()" size="mini" v-if="content.boxId==4||content.boxId==5">彻底删除</el-button>
        <el-button @click="delEmail()" size="mini" v-else>删 除</el-button>
      </h1>
      <h1 class="title main-title">主题：{{content.emailSubject}}</h1>
      <ul class="message" @mouseleave="showPanner(-1)">
        <!-- 已发送-->
        <div v-if="content.emailType==0">
          <li><span>发件人：</span>
            <div class="commonText">{{content.senderEmail}}</div>
          </li>
          <li><span @mouseover="showPanner(-1)">收件人：</span>
            <div class="box">
              <div class="box-one" v-for="item,index in showPeople.addressMan" :key="index"
                   @mouseover="showPanner(item.email,0)">
                <div class="box-detail">
                  <a v-if="item.hasOwnProperty('id')">
                    <img v-if="item.type ==0" title="陌生人"
                         src="../../../../public/img/email/icon/icon-people.png" class="delivery-img"
                         alt="陌生人">
                    <img v-else-if="item.type ==4" title="公海客户"
                         src="../../../../public/img/email/icon/icon-common.png" class="delivery-img"
                         alt="公海客户">
                    <img v-else-if="item.type ==2" title="同事建档客户"
                         src="../../../../public/img/email/icon/icon-worker.png" class="delivery-img"
                         alt="同事建档客户">
                    <img v-else-if="item.type ==3" title="共享客户"
                         src="../../../../public/img/email/icon/icon-share.png" class="delivery-img"
                         alt="共享客户">
                    <img v-else title="建档客户" src="../../../../public/img/email/icon/icon-customer.png"
                         class="delivery-img" alt="建档客户">
                  </a>
                  <img v-else src="../../../../public/img/email/icon/icon-people.png" alt="">
                  <b>{{filterLog(item)}}</b>
                </div>
              </div>
            </div>
          </li>
        </div>
        <!-- 收件箱-->
        <div v-else>
          <li><span @mouseover="showPanner(-1)">发件人：</span>
            <div class="box">
              <div class="box-one" v-for="item,index in showPeople.senderMan" :key="index"
                   @mouseover="showPanner(item.email,1)">
                <div class="box-detail">
                  <a v-if="item.hasOwnProperty('id')">
                    <img v-if="item.type ==0" title="未建档客户"
                         src="../../../../public/img/email/icon/icon-people.png" class="delivery-img"
                         alt="未建档客户">
                    <img v-else-if="item.type ==4" title="公海客户"
                         src="../../../../public/img/email/icon/icon-common.png" class="delivery-img"
                         alt="公海客户">
                    <img v-else-if="item.type ==2" v-else title="同事建档客户"
                         src="../../../../public/img/email/icon/icon-worker.png" class="delivery-img"
                         alt="同事建档客户">
                    <img v-else-if="item.type ==3" title="共享客户"
                         src="../../../../public/img/email/icon/icon-share.png" class="delivery-img"
                         alt="共享客户">
                    <img v-else title="已建档客户" src="../../../../public/img/email/icon/icon-customer.png"
                         class="delivery-img" alt="已建档客户">
                  </a>
                  <img v-else src="../../../../public/img/email/icon/icon-people.png" alt="">
                  <b>{{filterLog(item)}}<b v-show="content.alibabaInquiry">[feedback@service.alibaba.com]</b> </b>
                </div>
              </div>
            </div>
          </li>
          <li><span @mouseover="showPanner(-1)">收件人：</span>
            <div class="box">
              <div class="box-one" v-for="item,index in showPeople.addressMan" :key="index">
                <div class="box-detail" v-if="item.state==1">
                  <b>{{filterLog(item)}}</b>
                </div>
                <div class="box-detail" v-else @mouseover="showPanner(item.email,0)">
                  <a v-if="item.hasOwnProperty('id')">
                    <img v-if="item.type ==0" title="未建档客户"
                         src="../../../../public/img/email/icon/icon-people.png" class="delivery-img"
                         alt="未建档客户">
                    <img v-else-if="item.type ==4" title="公海客户"
                         src="../../../../public/img/email/icon/icon-common.png" class="delivery-img"
                         alt="公海客户">
                    <img v-else-if="item.type ==2" v-else title="同事建档客户"
                         src="../../../../public/img/email/icon/icon-worker.png" class="delivery-img"
                         alt="同事建档客户">
                    <img v-else-if="item.type ==3" title="共享客户"
                         src="../../../../public/img/email/icon/icon-share.png" class="delivery-img"
                         alt="共享客户">
                    <img v-else title="已建档客户" src="../../../../public/img/email/icon/icon-customer.png"
                         class="delivery-img" alt="已建档客户">
                  </a>
                  <img v-else src="../../../../public/img/email/icon/icon-people.png" alt="">
                  <b>{{filterLog(item)}}</b>
                </div>
              </div>
            </div>
          </li>
        </div>
        <li v-show="content.emailCarbonCopy"><span @mouseover="showPanner(-1)">抄 送：</span>
          <div class="box">
            <div class="box-one" href="javascript:void(0)" v-for="item,index in showPeople.carbonMan" :key="index">
              <div class="box-detail" v-if="item.state==1">
                <b>{{filterLog(item)}}</b>
              </div>
              <div class="box-detail" v-else @mouseover="showPanner(item.email,2)">
                <a v-if="item.hasOwnProperty('id')">
                  <img v-if="item.type ==0" title="陌生人"
                       src="../../../../public/img/email/icon/icon-people.png" class="delivery-img"
                       alt="陌生人">
                  <img v-else-if="item.type ==4" title="公海客户"
                       src="../../../../public/img/email/icon/icon-common.png" class="delivery-img"
                       alt="公海客户">
                  <img v-else-if="item.type ==2" v-else title="同事建档客户"
                       src="../../../../public/img/email/icon/icon-worker.png" class="delivery-img"
                       alt="同事建档客户lla">
                  <img v-else-if="item.type ==3" title="共享客户"
                       src="../../../../public/img/email/icon/icon-share.png" class="delivery-img"
                       alt="共享客户">
                  <img v-else title="建档客户" src="../../../../public/img/email/icon/icon-customer.png"
                       class="delivery-img" alt="建档客户">
                </a>
                <img v-else src="../../../../public/img/email/icon/icon-people.png" alt="">
                <b>{{filterLog(item)}}</b>
              </div>
              <!-- 弹出框-->
            </div>
          </div>
        </li>
        <li v-show="content.emailSecretDelivery&&content.emailType==0"><span @mouseover="showPanner(-1)">密 送：</span>
          <div class="box">
            <div class="box-one" href="javascript:void(0)" v-for="item,index in showPeople.secretMan" :key="index">
              <div class="box-detail" v-if="item.state==1">
                <b>{{filterLog(item)}}</b>
              </div>
              <div class="box-detail" v-else @mouseover="showPanner(item.email,3)">
                <a v-if="item.hasOwnProperty('id')">
                  <img v-if="item.type ==0" title="未建档客户"
                       src="../../../../public/img/email/icon/icon-people.png" class="delivery-img"
                       alt="未建档客户">
                  <img v-else-if="item.type ==4" title="公海客户"
                       src="../../../../public/img/email/icon/icon-common.png" class="delivery-img"
                       alt="公海客户">
                  <img v-else-if="item.type ==2" v-else title="同事建档客户"
                       src="../../../../public/img/email/icon/icon-worker.png" class="delivery-img"
                       alt="同事建档客户lla">
                  <img v-else-if="item.type ==3" title="共享客户"
                       src="../../../../public/img/email/icon/icon-share.png" class="delivery-img"
                       alt="共享客户">
                  <img v-else title="已建档客户" src="../../../../public/img/email/icon/icon-customer.png"
                       class="delivery-img" alt="已建档客户">
                </a>
                <img v-else src="../../../../public/img/email/icon/icon-people.png" alt="">
                <b>{{filterLog(item)}}</b>
              </div>
              <!-- 弹出框-->
            </div>
          </div>
        </li>
        <li><span>时 间：</span>
          <div class="commonText">{{content.sendTime}}</div>
        </li>
        <li v-show="content.emailHtmlpicList.length>0"><span>附 件：</span>
          <div class="else-file-get">共{{content.emailHtmlpicList.length}}个文件
            (<a v-for="item in content.emailHtmlpicList" href="javascript:void(0)" :title="`下载附件${item.picName}`" @click="look(item)"
                class="file-name">{{item.picName}};</a>)
          </div>
        </li>
      </ul>
      <!-- 显示追踪地址-->
      <div class="send-state" v-show="openList.length>0">
        <p>追踪记录
          于北京时间：{{openRow.createTime}}（当地时间：{{openRow.viewTime}}）被打开，打开地点：{{openRow.viewAddress}}（{{openRow.ipAddress}}）--共{{openList.length}}次
          <span @click="isTrace=!isTrace">查看详情</span></p>
        <!-- 表格展示-->
        <table v-show="isTrace">
          <thead>
          <tr>
            <th>查看地点</th>
            <th>查看当地时间</th>
            <th>查看北京时间</th>
            <th>IP地址</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="item,index in openList">
            <td>{{item.viewAddress}}</td>
            <td>{{item.viewTime}}</td>
            <td>{{item.createTime}}</td>
            <td>{{item.ipAddress}}</td>
          </tr>
          </tbody>
        </table>
      </div>
      <!-- 显示发送状态-->
      <div class="send-state" v-show="content.boxId==3">
        <div v-if="content.bounceId!=''&&content.errorMessage!=''">
          <p>发送状态：发送失败 &nbsp;&nbsp;&nbsp;很抱歉，您发的邮件被退回！
            <span @click="lookExit">查看退信邮件</span></p>
        </div>
        <div v-else>
          <p>发送状态：{{content.errorMessage==''?'发送成功':'发送失败'}}
            <span v-show="content.errorMessage!=''" @click="open=!open">查看详情</span></p>
          <p v-show="content.errorMessage!=''&&open" style="color: red">错误信息：{{content.errorMessage}}</p>
        </div>
      </div>
      <!-- 内容滚动区域-->
      <div class="scroll-area">
        <iframe :src="`/api/blade-email/html/content?id=${mailId}&ip=${this.host}&Blade-Auth=${token}`" width="100%"
                height="600px"></iframe>
      </div>
      <!-- 附件展示-->
      <div class="else" v-show="content.emailHtmlpicList.length>0">
        <h1 class="title-else" style="margin-bottom: 10px">附件 (共{{content.emailHtmlpicList.length}}个)</h1>
        <MailFileDetail :list="content.emailHtmlpicList"></MailFileDetail>
      </div>
      <!--快速回复 emailType 0 发件- 1 收件-->
      <div v-if="content.emailType==1">
        <el-input v-model="quickEmail" :placeholder="`快速回复给${content.senderNickName}`" type="textarea" :rows="4">
        </el-input>
        <div style="display: flex;justify-content: space-between;">
          <el-button size="mini" type="primary" @click="sendEmail()" title="快速回复给客户">快速回复</el-button>
          <el-button size="mini" style="float: right" title="进入邮件详情回复" @click="toBack(0)">回复全部</el-button>
        </div>
      </div>
    </div>
    <!--  收件箱-->
    <editCompany ref="editCompany" :currentEmail="currentEmail" @relationCustomer="relationCustomer"
                 title="新增客户" v-show="content.boxId==0"></editCompany>
    <!-- 发件箱-->
    <editCompany ref="editCompanys" :currentEmail="currentEmail" @relationCustomer="relationCustomer"
                 title="新增客户" v-show="content.boxId==3"></editCompany>
    <!-- 添加已有客户-->
    <DialogAddCustomer ref="dialogAddCustomer" @relationCustomer="relationCustomer"></DialogAddCustomer>
    <EditCompany :show="editCom_show" @updata="updateCompany" title="编辑客户" :id="custid" v-if="companyShow"
                 ref="editHasCompany"></EditCompany>
    <!-- 新增标签-->
    <LabelDialog ref="labelDialog" @newLabel="newLabel"></LabelDialog>
    <!-- 分发弹框-->
    <TranslateDialog ref="translateDialog"></TranslateDialog>
    <!-- 归档文件-->
    <DocDialog ref="docDialog" @dealFoldID="dealFoldID"></DocDialog>
    <!--  时间选择-->
    <el-dialog :visible.sync="dialogVisible" width="500px"
               :close-on-click-modal="false" :close-on-press-escape='false'
               title="选择稍后处理的时间">
      <el-form ref="form" label-width="100px">
        <el-form-item label="自定义时间" style="margin: 40px 0">
          <el-date-picker size="mini" v-model="nextTime" align="center" value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="自定义时间" :picker-options="pickerOptions"
                          type="datetime" :clearable="false">
          </el-date-picker>
          <!-- 底部按钮-->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button @click="cancel" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="submitTime">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 密送回复弹窗-->
    <DialogSendEmail ref="dialogSendEmail" @toBack="toBack"></DialogSendEmail>
    <!--    移入私海-->
    <DialogMovePerson @relationCustomer="relationCustomer" ref="dialogMovePerson"></DialogMovePerson>
    <!--添加 跟进记录-->
    <DialogFollow ref="DialogFollow"></DialogFollow>
  </div>
</template>

<script>
    import {canCelCust} from '@/api/customer'
    import EditCompany from '@/components/customer/company'
    import DialogAddCustomer from "@/components/mail/DialogAddCustomer";
    import MailFileDetail from '@/components/mail/file/MailFileDetail'
    import {sendEmail, relationCustomer, getRead, relationEmail} from "@/api/mail/write";
    import editCompany from '@/components/customer/company/emailAddUser'
    import {getDate, getNext, getHour, getNextDate, filterSameEmail} from "@/util/util"
    import LabelDialog from "@/components/mail/dialog/LabelDialog";
    import DocDialog from "@/components/mail/dialog/DocDialog";
    import {
        nextEmail,
        labelEmail,
        removeEmail,
        delEmail,
        emptyEmail,
        getMailDetail,
        hasBackEmail,
        getEmailStream,
        getEmailIP
    } from "@/api/mail/make"
    import TranslateDialog from "@/components/mail/dialog/TranslateDialog";
    import DialogSendEmail from "@/components/mail/DialogSendEmail";
    import DialogMovePerson from "@/components/mail/DialogMovePerson";
    import CustomerInfo from "@/components/mail/relation/CustomerInfo";
    import DialogFollow from '@/components/mail/relation/DialogFollow'
    import {mapState, mapGetters} from 'vuex'
    import {getToken} from '@/util/auth'
    import {fileStreamDown} from '@/api/mail/'
    export default {
        name: "detail",
        components: {
            MailFileDetail,
            DialogAddCustomer,
            editCompany,
            LabelDialog,
            TranslateDialog,
            DocDialog,
            DialogSendEmail,
            EditCompany,
            DialogMovePerson,
            CustomerInfo,
            DialogFollow
        },
        data() {
            return {
                isComplete:false,
                currentFrag: 1,
                total: 0,
                currentPage: 1,
                custid: '',
                editCom_show: false,
                companyShow: true,
                isTrace: false,
                open: false,
                content: {
                    boxId: '',
                    addresseeEmail: '',//收件人邮箱数组
                    emailCarbonCopy: '',//抄送数组
                    emailSecretDelivery: '',//密送数组
                    emailHtmlpicList: [],//附件列表
                },
                quickEmail: '',
                Width: '100%',
                relationList: [],
                customerList: [],
                currentCustomer: '',
                customer: {
                    name: '相关往来客户',
                    email: '客户邮箱'
                },
                //新增按钮
                targetTime: '',
                todayTime: '',
                nextWeek: '',
                nextTime: '',
                targetLabel: '',
                dialogVisible: false,
                targetRemove: '',
                moveArchiveFolderId: '',
                isEnd: false,
                pickerOptions: {
                    disabledDate: time => {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                },
                isMine: false,
                myRelation: [],
                editorContent: '',
                isEndAll: false,
                host: '',
                mailId: '',
                token: '',
                openList: [],//追踪列表
                openRow: {},//最新一条
                showPeople: {
                    senderMan: [],//收件箱
                    addressMan: [],
                    carbonMan: [],
                    secretMan: []
                },
                frag0: -1,//收件
                frag1: -1,//发件
                frag2: -1,//抄送
                frag3: -1,//密送
                currentEmail: '',
                loading: false,
                isLoading: false
            }
        },
        computed: {
            ...mapState(['common']),
            ...mapGetters(["userInfo"]),
        },
        watch: {
            dialogVisible(val, old) {
                if (!val) {
                    this.targetTime = ''
                }
            },
        },
        created() {
            this.mailId = this.$route.query.id;
            if (process.env.NODE_ENV == 'production') {//生成环境
                this.host = 'https://' + location.host
            }else{
                this.host = 'http://192.168.0.6:1888'
            }
            this.getDetail(this.mailId);
            this.todayTime = getHour();
            this.nextWeek = getNextDate();
            this.token = "bearer " + getToken();
        },
        methods: {
            //移入私海
            movePerson(custid) {
                this.$refs.dialogMovePerson.init(custid);
            },
            //取消共享
            cancelShare(custid) {
                this.$confirm('取消共享后，您将看不到选中客户的所有信息，您确定要取消共享吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    canCelCust(custid).then(res => {
                        if (res.data.success) {
                            this.relationCustomer();
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            });
                        }
                    })
                })
            },
            editHasInfo(id) {
                this.custid = id;
                this.editCom_show = true
                this.$refs.editHasCompany.getInit(this.custid);
            },
            updateCompany(value) {
                if (value) {
                    this.relationCustomer();
                }
                this.editCom_show = false
                this.companyShow = false
                this.$nextTick(() => {
                    this.companyShow = true
                    this.custid = ''
                })
            },
            showPanner(email, type) {
                this.frag0 = this.frag1 = this.frag2 = this.frag3 = -1;
                switch (type) {
                    case 0:
                        this.frag0 = email;
                        break;
                    case 1:
                        this.frag1 = email;
                        break;
                    case 2:
                        this.frag2 = email;
                        break;
                    case 3:
                        this.frag3 = email;
                        break;
                    default:
                        return;
                }
            },
            look(row){
                fileStreamDown(row.id).then(res => {
                    var blob = new Blob([res.data]);
                    var downloadElement = document.createElement('a');
                    var href = window.URL.createObjectURL(blob); // 创建下载的链接
                    downloadElement.href = href;
                    downloadElement.download = row.picName; // 下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); // 点击下载
                    document.body.removeChild(downloadElement); // 下载完成移除元素
                    window.URL.revokeObjectURL(href); // 释放掉blob对象
                })
            },
            lookExit() {
                let routeUrl = this.$router.resolve({
                    path: `/mail/send/review`,
                    query: {
                        id: this.content.bounceId
                    }
                });
                window.open(routeUrl.href, '_blank');
            },
            //作为附件发送
            elseEmail() {
                this.isLoading = true;
                getEmailStream(this.content.temailInfoId).then(res => {
                    this.isLoading = false;
                    if (res.data.success) {
                        const result = res.data.data;
                        const params = {
                            emailSubject: "Fw:" + this.content.emailSubject,
                            emailHtmlpicList: [{
                                picName: result.fileName,
                                fileSize: result.fileSize,
                                fileGuid: result.fileUrl
                            }]
                        };
                        this.$router.push({
                            path: '/mail/write/index',
                            query: {
                                info:JSON.stringify(params),
                                where:1
                            }
                        })
                    }
                }).catch(err => {
                    this.isLoading = false;
                })
            },
            filterSame(id) {
                let index = -1;
                for (let i in this.common.emailListTab.list) {
                    const item = this.common.emailListTab.list[i];
                    if (item.id == id) {
                        index = i;
                    }
                }
                return index;
            },
            back() {
                if (sessionStorage.getItem("lastpath")) {
                    this.$router.push(sessionStorage.getItem("lastpath"))
                } else {
                    this.$router.go(-1)
                }
            },
            checkHtml(htmlStr) {
                var reg = /<[^>]+>/g;
                return reg.test(htmlStr);
            },
            dealInfo() {//获取所有客户addresseeEmail emailCarbonCopy emailSecretDelivery
                const send = [this.content.senderEmail];
                const address = this.content.addresseeEmailArray;
                const carbon = this.content.emailCarbonCopy ? this.content.emailCarbonCopy.split(',') : [];
                const secret = this.content.emailSecretDelivery ? this.content.emailSecretDelivery.split(',') : [];
                if (this.content.emailType == 1) {//收件箱
                    let end = [];
                    let target = this.filterRule(this.content.addresseeEmailArray);
                    for (let i = 0, len = target.length; i < len; i++) {
                        let item = target[i];
                        let index = -1;
                        for (let j = 0, len1 = this.common.emailList.length; j < len1; j++) {
                            const item1 = this.common.emailList[j];
                            if (item == item1.emailAddr) {//匹配
                                index = j;
                            }
                        }
                        if (index == -1) {
                            end.push(item)
                        }
                    }
                    this.customerList = send.concat(carbon, secret, end);
                } else {//已发送
                    this.customerList = address.concat(secret, carbon)
                }
                this.customerList = this.filterRule(this.customerList);

            },
            rollBack() {//回复 - 发件人变收件人
                let sendMan;
                if (this.content.emailType == 1) {//收件箱
                    sendMan = this.content.userEmail;
                } else {
                    sendMan = this.content.senderEmail;
                }
                this.$router.push({
                    path: '/mail/write/index',
                    query: {
                        senderEmail: sendMan,
                        customer: this.content.senderEmail,
                        emailSubject: "Re:" + this.content.emailSubject,
                        emailContent: `${this.common.sign}` + this.getEndEmail() + this.content.emailContent,
                        emailOriginalId: this.content.temailInfoId,
                        where:1
                    }
                })
            },
            getEndEmail() {
                let emailCarbonCopy = this.content.emailCarbonCopy ? this.content.emailCarbonCopy.split(',') : [];//目标抄送数组
                let str = `<br><br><br>---------------- Original ----------------<br><div class="previous" style="color: #000000;font-size: 14px;font-family: Arial;line-height: 1.7;margin-bottom: 20px;background-color: #dddddd45;
    padding: 0 5px;">From: ${this.content.senderEmail}<br>Date: ${this.content.sendTime}<br>To:${this.filterRule(this.content.addresseeEmailArray).join(";")}`;
                if (emailCarbonCopy.length > 0) {
                    let cc = `<br>CC:${this.filterRule(emailCarbonCopy).join(";")}`;
                    str += cc;
                }
                const subject = `<br>Subject: ${this.content.emailSubject}</div>`;
                str += subject;
                return str;
            },
            getDetail(id) {
                getMailDetail(parseInt(id)).then(res => {
                    if (res.data.success) {
                        this.content = res.data.data;
                        this.dealIt();
                        //判断是否是已发送并且一打开
                        if (this.content.emailType==0 && this.content.sendStatus == 0 && this.content.openStatus == 1) {
                            this.getOpenIP(id)
                        } else {
                            this.openList = []
                        }
                    }
                })
            },
            getOpenIP(id) {
                getEmailIP(id).then(res => {
                    if (res.data.success) {
                        this.openList = res.data.data;
                        this.openRow = this.openList[0];
                    }
                })
            },
            dealIt() {
                this.dealInfo();
                if (parseInt(this.content.readStatus) == 1) {
                    //已读未读处理
                    this.getRead();
                }
                //设为已回执
                if (parseInt(this.content.emailReceipt) == 1) {
                    this.hasBackEmail();
                }
                //收件箱，已发送 ， 来自客户
                this.relationCustomer();//获取客户列表
                this.isEndAll = true;
                //判断是否为回执邮件 this.content.emailReceipt==1  回执
                if (this.content.emailReceipt == 1 && this.content.emailType == 1) {//弹窗
                    this.$confirm(`<div style="margin: 20px 10px;"><p style="line-height: 30px;font-size: 15px;color: #333">发件人希望得到您的回执，是否发送？</p></div>`, '回执邮件', {
                        dangerouslyUseHTMLString: true,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '发 送',
                        cancelButtonText: '不发送',
                    }).then(() => {
                        this.toSend();
                    }).catch(() => {
                    })
                }
            },
            hasBackEmail() {
                hasBackEmail({temailInfoIds: [this.content.temailInfoId]})
            },
            toSend() {
                let params = {
                    addresseeEmail: [this.content.senderEmail],//收件人邮箱数组
                    emailCarbonCopy: [],//抄送数组
                    emailSecretDelivery: [],//密送数组
                    emailHtmlpicList: [],//附件列表
                    emailSubject: `Re:${this.content.emailSubject}`,//主题
                    emailContent: '您发送的这封邮件已经被打开',//邮件内容
                    emailReceipt: 0,//是否回执 0-默认不回执，1-回执
                    emaileDelivery: 0,//投递状态  （紧急与非紧急） 0-默认常规，2-紧急
                    monocula: 0,//群发单显
                    emailTrack: 0,//0 - 不追踪  1 - 追踪
                    emailSendTiming: '', //邮件定时发送时间
                    senderEmail: this.content.userEmail,//发件人邮箱
                    senderNickName: '',//发件人昵称
                };
                params.emailContent = encodeURIComponent(params.emailContent);
                sendEmail(params).then(res => {
                    if (res.data.success) {
                        this.bus.$emit('refreshEmailNum')
                        this.$message({duration: 1500, message: res.data.msg, type: 'success'});
                    } else {
                        this.$message({
                            duration: 1500,
                            message: res.data.msg,
                            type: "success"
                        });
                        params.emailContent = decodeURIComponent(params.emailContent);
                    }
                }).catch(err => {
                    params.emailContent = decodeURIComponent(params.emailContent);//防止二次提交
                })
            },
            handleChange(val) {
                this.moveArchiveFolderId = val[val.length - 1];
            },
            dealFoldID(id) {
                this.moveArchiveFolderId = id;
                this.moveEmail();
            },
            moveEmail() {
                removeEmail({
                    boxId: this.moveArchiveFolderId && this.content.boxId != 7 ? 7 : this.targetRemove,
                    temailInfoIds: [this.content.temailInfoId],
                    archiveFolderId: this.moveArchiveFolderId
                }).then(res => {
                    if (this.targetRemove == '4') {//已删除
                        const result = this.dealNewList();
                        this.$store.commit('SET_EMAILLISTTAB', {
                            type: 2, list: result.arr, index: result.index
                        })
                    }
                    this.dealResult(res)
                }).catch(err => {
                    console.log(err)
                });
            },
            //添加已有客户
            addHasCustomer(email) {
                this.$refs.dialogAddCustomer.getGroup(email);
            },
            //新建客户
            newCustomer(email) {
                this.currentEmail = email;
                if (this.content.boxId == 0) {
                    this.$refs.editCompany.init(email);
                } else {
                    this.$refs.editCompanys.init(email);
                }
            },
            //已读
            getRead() {
                getRead({temailInfoIds: [this.content.temailInfoId]}).then(res => {
                    this.bus.$emit('refreshEmailNum')
                    this.bus.$emit('getEmail');
                })
            },
            //快速回复邮件
            sendEmail() {
                if (!this.quickEmail) {
                    this.$message({message: '请输入快速回复的内容', type: "success"});
                    return;
                }
                let params = {
                    addresseeEmail: [this.content.senderEmail],//收件人邮箱数组
                    emailCarbonCopy: [],//抄送数组
                    emailSecretDelivery: [],//密送数组
                    emailHtmlpicList: [],//附件列表
                    emailSubject: 'Re:' + this.content.emailSubject,//主题 - 回复：
                    emailContent: '',//邮件内容
                    emailReceipt: 0,//是否回执 0-默认不回执，1-回执
                    emaileDelivery: 0,//投递状态  （紧急与非紧急） 0-默认常规，1-紧急
                    monocula: 0,//群发单显
                    emailTrack: 0,//0 - 不追踪  1 - 追踪
                    emailSendTiming: '', //邮件定时发送时间
                    senderEmail: this.content.userEmail,//发件人邮箱
                    senderNickName: this.userInfo.account,//发件人昵称
                    boxID: '',
                    emailOriginalId: this.content.temailInfoId
                }
                this.$confirm('立即发送邮件给客户?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    params.emailContent = encodeURIComponent(this.quickEmail + this.getEndEmail() + this.content.emailContent);
                    sendEmail(params).then(res => {
                        if (res.data.success) {
                            //刷新
                            this.bus.$emit('refreshEmailNum')
                            this.$message({message: '邮件发送成功', type: 'success'});
                            this.quickEmail = '';
                        } else {
                            params.emailContent = decodeURIComponent(params.emailContent);
                        }
                    }).catch(err => {
                        params.emailContent = decodeURIComponent(params.emailContent);
                    })
                }).catch(() => {
                });

            },
            //再次编辑
            toEdit() {
                let targetContent = JSON.parse(JSON.stringify(this.content));
                targetContent.emailContent = this.content.emailContent;
                targetContent.emailSubject = this.content.emailSubject;
                targetContent.temailInfoId = '';
                let addresseeEmailArray = this.content.addresseeEmailArray;
                let arr = [], arr1 = [];
                this.content.temailInfoId = '';
                if (this.content.emailType == 0) {//发件箱
                    targetContent.emailSecretDelivery = '';
                }
                addresseeEmailArray.map((item, index) => {
                    if (item.indexOf('<') != -1) {//<1749846095@qq.com>
                        item = item.split('<')[1];
                        item = item.split('>')[0];
                    }
                    arr.push(item);
                })
                let emailCarbonCopy = this.content.emailCarbonCopy ? this.content.emailCarbonCopy.split(',') : [];//目标抄送数组
                emailCarbonCopy.map((item, index) => {
                    if (item.indexOf('<') != -1) {//<1749846095@qq.com>
                        item = item.split('<')[1];
                        item = item.split('>')[0];
                    }
                    if (item != this.content.userEmail) {
                        arr1.push(item);
                    }
                })
                targetContent.addresseeEmail = arr.join(',');
                targetContent.emailCarbonCopy = arr1.join(',');
                targetContent.emailSendTiming = '';
                this.$router.push({
                    path: '/mail/write/edit',
                    query: {
                        row: JSON.stringify(targetContent)
                    }
                })
            },
            //回复全部
            toBack(type) {
                let targetContent = JSON.parse(JSON.stringify(this.content));
                targetContent.emailContent = `${this.common.sign}` + this.getEndEmail() + this.content.emailContent;
                targetContent.emailSubject = 'Re:' + this.content.emailSubject;
                targetContent.temailInfoId = '';
                targetContent.emailOriginalId = this.content.temailInfoId;
                let arr = [], arr1 = [], frag = -1, isChao = -1, isShou = -1;
                let addresseeEmailArray = this.content.addresseeEmailArray;
                let emailCarbonCopy = this.content.emailCarbonCopy ? this.content.emailCarbonCopy.split(',') : [];//目标抄送数组
                addresseeEmailArray.map((item, index) => {
                    if (item.indexOf('<') != -1) {//<1749846095@qq.com>
                        item = item.split('<')[1];
                        item = item.split('>')[0];
                    }
                    if (item != this.content.userEmail) {
                        arr1.push(item);
                    } else {
                        isShou = index;
                        frag = index;
                    }
                })
                emailCarbonCopy.map((item, index) => {
                    if (item.indexOf('<') != -1) {//<1749846095@qq.com>
                        item = item.split('<')[1];
                        item = item.split('>')[0];
                    }
                    if (item != this.content.userEmail) {
                        arr.push(item);
                    } else {
                        isChao = index;
                        frag = index;
                    }
                })
                //判断是否多个收件人 -
                if (this.content.emailType == 1) {//收件箱
                    targetContent.addresseeEmail = [this.content.senderEmail].join(',');//xxz15268533757@sina.com
                    let end = arr.concat(arr1);//超送
                    if (frag == -1 && parseInt(type) != 1) {//我是密送 -弹窗
                        this.$refs.dialogSendEmail.init(this.content);
                        return;
                    } else if (isChao != -1) {//抄送 - 重组抄送
                        let demo = [];
                        end.map((item) => {
                            if (item != this.content.userEmail) {
                                demo.push(item);
                            }
                        })
                        targetContent.emailCarbonCopy = demo.join(',');
                    }
                    if (isShou != -1) {//收件人
                        let demo = [];
                        end.map((item) => {
                            if (item != this.content.userEmail) {
                                demo.push(item);
                            }
                        })
                        end = demo;
                    }
                    targetContent.monocular = 0;
                    targetContent.emailReceipt = 0;
                    targetContent.emaileDelivery = 0;
                    targetContent.emailCarbonCopy = end.join(',');
                } else {//发件箱 - 清除密送人 - 发件人还是一样
                    targetContent.emailSecretDelivery = "";
                }
                targetContent.emailSendTiming = '';
                targetContent.emailHtmlpicList = [];
                this.$router.push({
                    path: '/mail/write/edit',
                    query: {
                        row: JSON.stringify(targetContent)
                    }
                })
            },
            //切换人
            changeMan(row) {
                if (row.email == this.customer.email) return;
                this.customer = row;
                let params = {allEmailList: [row.email]}
                this.getTargetEmail(params)
            },
            //切换邮件
            change(row) {
                const ID = row.temailInfoId.toString();//row.id - 临时
                if (this.filterHas(ID) == -1) {
                    this.$store.commit('SET_EMAILLISTTAB', {
                        type: 1, row: {
                            id: ID,
                            title: row.emailSubject,
                            state:1,
                            close: true
                        }
                    })
                }else{
                    this.$store.commit('SET_EMAILLISTTAB', {type:0,current:ID})
                }
            },
            filterHas(ID){
                let index = -1;
                for (let i in this.common.emailListTab.list) {
                    const item = this.common.emailListTab.list[i];
                    if (item.id == ID) {
                        index = i;
                    }
                }
                return index;
            },
            //获取客户列表
            relationCustomer(...type) {
                let params = {emailList: this.customerList.join(',')};
                relationCustomer(params).then(res => {
                    if (res.data.success) {
                        this.showPeople = {
                            senderMan: [],//收件箱
                            addressMan: [],
                            carbonMan: [],
                            secretMan: []
                        };
                        const result = res.data.data;//this.myRelation - email
                        //对比收件人，抄送人，密送人
                        const address = this.filterRule(this.content.addresseeEmailArray);
                        const sender = [...[this.content.senderEmail], ...address];
                        const carbon = this.content.emailCarbonCopy ? this.filterRule(this.content.emailCarbonCopy.split(',')) : [];
                        const secret = this.content.emailSecretDelivery ? this.filterRule(this.content.emailSecretDelivery.split(',')) : [];
                        let addressMan = [], senderMan = [], carbonMan = [], secretMan = [], targetSend = '';
                        for (let i = 0, len = result.length; i < len; i++) {
                            const item = result[i];
                            if (address.includes(item.email) && this.content.emailType == 0) {//已发送
                                addressMan.push(item)
                            }
                            if ((sender.includes(item.email)) && this.content.emailType == 1) {//收件箱
                                senderMan.push(item)
                            }
                            if (carbon.includes(item.email)) {
                                carbonMan.push(item)
                            }
                            if (secret.includes(item.email)) {
                                secretMan.push(item)
                            }
                            if (this.content.senderEmail == item.email) {
                                targetSend = item;
                            }
                        }
                        if (this.content.emailType == 0) {//已发送
                            this.showPeople.addressMan = this.dealNewOld(address, addressMan);
                            if (type.length == 0) {
                                this.customer = this.showPeople.addressMan[0];
                            }
                        } else {//收件箱  - 我是收件人 - 判断多个收件人情况 - 发件人固定，不考虑  考虑收件人 addressEmail = []
                            const target = this.dealNewOld(sender, senderMan);
                            this.showPeople.addressMan = filterSameEmail(target);
                            //去除发件人一个 - this.showPeople.addressMan
                            let arr = [];
                            this.showPeople.addressMan.map((item, i) => {
                                if (item.email != this.content.senderEmail) {
                                    arr.push(item)
                                }
                            })
                            this.showPeople.addressMan = arr;
                            //发件人
                            if (targetSend != '') {//有
                                this.showPeople.senderMan = [targetSend];
                            } else {
                                this.showPeople.senderMan = [{
                                    email: this.content.senderEmail,
                                    linker: this.content.senderEmail.split('@')[0]
                                }];
                            }
                            if (type.length == 0) {
                                this.customer = this.showPeople.senderMan[0];
                            }
                        }
                        this.showPeople.carbonMan = filterSameEmail(this.dealNewOld(carbon, carbonMan));
                        this.showPeople.secretMan = filterSameEmail(this.dealNewOld(secret, secretMan));
                        console.log(this.showPeople)
                        if (type.length == 0) {
                            this.relationEmail();//获取往来邮件
                        }
                    }
                })
            },
            //分页获取往来邮件
            handleCurrent(val) {
                this.currentPage = val;
                this.relationEmail()
            },
            //1.获取往来邮件 - 判断
            relationEmail() {
                let params;
                if (this.content.boxId == 0 || this.content.boxId == 1) {//收件箱
                    params = {allEmailList: [this.content.senderEmail]}
                } else if (this.content.boxId == 3) {//发件箱
                    params = {allEmailList: [this.customer.email]}
                }
                params = {...params, current: this.currentPage, size: 15}
                this.getTargetEmail(params)
            },
            //2.获取往来邮件 - 获取
            getTargetEmail(params) {
                this.loading = true;
                relationEmail(params).then(res => {
                    this.loading = false;
                    if (res.data.success) {
                        const result = res.data.data;
                        this.relationList = result.records;
                        this.total = result.total;
                        this.isEnd = this.total == 0;
                    }
                }).catch(err => {
                    this.loading = false;
                })
            },
            dealNewOld(arr, old) {//arr [1,2,3] old[{},{}]
                let newMan = [];
                if (arr.length == 0 && old.length == 0) return [];
                if (old.length == 0) {
                    for (let i = 0, len = arr.length; i < len; i++) {
                        newMan.push({email: arr[i], linker: arr[i].split("@")[0]})
                    }
                    return newMan;
                }
                for (let i = 0, len = arr.length; i < len; i++) {
                    const item = arr[i];
                    let row = '';
                    for (let j = 0, len1 = old.length; j < len1; j++) {
                        const items = old[j];
                        if (item == items.email) {//存在
                            row = items;
                        }
                    }
                    if (row != '') {
                        newMan.push(row)
                    } else {
                        newMan.push({
                            email: item,
                            linker: item.split('@')[0]
                        })
                    }
                }
                return newMan;
            },
            dealContent(str) {
                let reg = /<(style)(?:[^>]*)?>([\s\S]*?)(?:<\/\1>[^\"\']|<\/\1>$)/ig;
                let msg = str.replace(reg, '');
                let reg1 = new RegExp("<[^>]+>", "g");
                msg = msg.replace(reg1, '');
                return msg;
            },
            //分发
            translate() {
                this.$refs.translateDialog.init(this.content.temailInfoId,'emailListOutTab')
            },
            //移动邮件
            toRemove(val) {
                if (val == '7') { //选择归档文件夹
                    this.$refs.docDialog.init();
                    this.targetRemove = '';
                } else {
                    this.moveEmail();
                }
            },
            //删除邮件
            delEmail() {
                this.$confirm('是否删除该邮件?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    delEmail([this.content.temailInfoId]).then(res => {
                        if (res.data.success) {
                            const result = this.dealNewList();
                            this.$store.commit('SET_EMAILLISTTAB', {
                                type: 2, list: result.arr, index: result.index
                            })
                        }
                        this.dealResult(res)
                    }).catch(err => {
                        console.log(err)
                    })
                }).catch(() => {
                });
            },
            dealNewList() {
                let list = this.common.emailListTab.list, arr = [], index;
                for (let i in list) {
                    const item = list[i];
                    if (item.id != this.id) {
                        arr.push(item)
                    } else {
                        index = i;
                    }
                }
                return {arr: arr, index: index}
            },
            emptyEmail() {
                this.$confirm('彻底删除该邮件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    emptyEmail([this.content.temailInfoId]).then(res => {
                        this.dealResult(res)
                        if (res.data.success) {
                            this.$router.go(-1)
                        }
                    }).catch(err => {
                        console.log(err)
                    });
                }).catch(() => {
                });
            },
            //标记为
            toLabel() {
                if (this.targetLabel == 'add') { //新增标签
                    this.$nextTick(() => {
                        this.$refs.labelDialog.init();
                    })
                    this.targetLabel = '';
                    return;
                }
                labelEmail({
                    tagId: this.targetLabel,
                    temailInfoIds: [this.content.temailInfoId]
                }).then(res => {
                    this.dealResult(res)
                }).catch(err => {
                    console.log(err)
                });
            },
            //稍后处理
            toNextDeal() {
                if (this.targetTime == '稍后处理') {
                    this.dialogVisible = true;
                } else {
                    this.submitTime()
                }
            },
            submitTime() {
                const time = this.getTime();
                if (time.indexOf('NaN') != -1) {//，没找到
                    this.$message({
                        type: "success",
                        message: '请选择自定义时间'
                    });
                    return;
                }
                this.targetTime = '';
                this.nextTime = '';
                this.dialogVisible = false;
                nextEmail({
                    processTime: time,
                    temailInfoIds: [this.content.temailInfoId]
                }).then(res => {
                    this.dealResult(res)
                }).catch(err => {
                    console.log(err)
                });
            },
            cancel() {
                this.dialogVisible = false;
                this.nextTime = '';
                this.targetTime = ''
            },
            getTime() {
                switch (this.targetTime) {
                    case '1':
                        return getDate(0) + " " + this.todayTime + ":00";
                    case '2':
                        return getDate(1) + " 08:00:00";
                    case '3':
                        return getDate(2) + " 08:00:00";
                    case '4'://下周
                        let result;
                        if (this.nextWeek == '一') {
                            result = getNext(1)
                        } else if (this.nextWeek == '二') {
                            result = getNext(2)
                        } else if (this.nextWeek == '三') {
                            result = getNext(3)
                        }
                        return result + " 08:00:00";
                    case '稍后处理':
                        return this.nextTime;
                    default:
                        return
                }
            },
            newLabel() {
                var labelID = this.common.labelList[0].id;
                labelEmail({
                    tagId: labelID,
                    temailInfoIds: [this.content.temailInfoId]
                }).then(res => {
                    this.dealResult(res)
                }).catch(err => {
                    console.log(err)
                });
            },
            filterLog(row) {
                if (row.email.indexOf('<') != -1) {
                    return row.linker + row.email
                } else {
                    return `${row.linker}<${row.email}>`
                }
            },
            filterRule(arr) {
                let result = [];
                arr.map((item, index) => {
                    if (item.indexOf('<') != -1) {//<1749846095@qq.com>
                        item = item.split('<')[1];
                        item = item.split('>')[0];
                    }
                    result.push(item);
                })
                return result;
            },
            dealResult(res) {
                this.targetLabel = '';
                this.targetRemove = '';
                if (res.data.success) {
                    this.bus.$emit('getEmail');
                    this.bus.$emit('refreshEmailNum');
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                } else {
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
  @import "../../../styles/reviewEmail";
  .detail{
    .detail-left{
      width: 100%;
    }
  }
  .send-state {
    margin-bottom: 10px;
    background-color: #2a97f914;
    padding: 10px 15px;
    border-radius: 5px;

    span {
      cursor: pointer;
      margin-left: 25px;
      color: #2a97f9;
      border-bottom: 1px solid #2a97f9;
    }

    p {
      line-height: 25px;
      font-size: 13px;
    }

    table {
      display: block;
      width: 100%;
      max-height: 250px;
      overflow-y: auto;

      tbody,
      thead {
        padding: 10px 30px;
        align-items: center;
        color: #333;
        font-size: 13px;
      }

      td,
      th {
        color: #2D3F50;
        padding: 6px 10px;
        text-align: center;
      }

      th {
        font-weight: bold;
        color: #232323;
      }
    }
  }
</style>
